package com.chartHandle.excelService.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.chartHandle.bean.*;
import com.chartHandle.config.SmokeOrderTemplate1Config;
import com.chartHandle.excelService.handle.ExportAllFileCellColorHandler;
import com.chartHandle.excelService.handle.MergeHandler;
import com.chartHandle.excelService.service.WriteOrderInfoInfoService;
import com.chartHandle.util.ExcelUtil;
import com.chartHandle.util.Util;
import com.projectCommon.bean.constant.ColorIndex;
import com.projectCommon.bean.easyExcel.ExcelSmokeInfo;
import com.projectCommon.util.commonUtil.StringUtils;
import com.projectCommon.util.springUtil.annotation.MethodEventDescription;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WriteOrderInfoServiceImpl implements WriteOrderInfoInfoService {
    @Autowired
    private SmokeOrderTemplate1Config smokeOrderTemplate1Config;

    @Override
    public byte[] writeOrderInfoTemplate1(List<ExcelSmokeInfo> baseInfo) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Map<String, Object> singleInfoMap = getDataMap(baseInfo);

        Map<PointXY, CellStyleWY> pointXYCellStyleWYHashMap = getExcelCellInfo(baseInfo, singleInfoMap);
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        ExportAllFileCellColorHandler exportAllFileCellColorHandler = new ExportAllFileCellColorHandler(pointXYCellStyleWYHashMap);
        exportAllFileCellColorHandler.setRows(Integer.parseInt(smokeOrderTemplate1Config.getHeadHeight()));

        // 读取txt配置文件的内容，将字段添加进去，然后处理一下行高  allotypeSmokeColor
        HashMap<String, String> repStrMaps = new HashMap<>();
        for (ColorIndex colorIndex : ColorIndex.values()) {
            if (colorIndex.index == smokeOrderTemplate1Config.getAllotypeSmokeColor()) {
                repStrMaps.put("allotypeSmokeColor", colorIndex.colorName);
                break;
            }
        }
        List<TemplateRemark> orderRemarks = smokeOrderTemplate1Config.getOrderRemarks();
        orderRemarks.add(0, new TemplateRemark());

        for (TemplateRemark orderRemark : orderRemarks) {
            List<String> contentList = orderRemark.getContentList();
            if (contentList == null) {
                continue;
            }
            StringBuilder content = new StringBuilder();
            for (int i = 0; i < contentList.size(); i++) {
                String contentLine = Util.replaceTxtStr(contentList.get(i), repStrMaps);
                contentList.set(i, contentLine);
                content.append(contentLine).append("\n");
            }
            orderRemark.setContent(content.toString());
        }

        // 设置一下行高
        List<RowObj> remarkRowHeight = getRemarkRowHeight(orderRemarks, baseInfo, smokeOrderTemplate1Config);

        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setWrapped(true);
        ExcelWriter excelWriterBuild = EasyExcel
                .write(outputStream)
                .withTemplate(new ByteArrayInputStream(smokeOrderTemplate1Config.getFileByte()))
                .excelType(ExcelTypeEnum.XLS)
                .registerWriteHandler(exportAllFileCellColorHandler)
                .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, headWriteCellStyle))
                .registerWriteHandler(new MergeHandler())
                .build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

        excelWriterBuild.fill(new FillWrapper("baseInfo", baseInfo), fillConfig, writeSheet);
        excelWriterBuild.fill(new FillWrapper("remarks", orderRemarks), fillConfig, writeSheet);
        excelWriterBuild.fill(singleInfoMap, writeSheet);
        excelWriterBuild.finish();
        ByteArrayOutputStream beautification = beautification(remarkRowHeight, outputStream.toByteArray());
        return beautification.toByteArray();
    }

    /**
     * 根据当前数据进行一个计算 转换
     * double的运算统一使用
     * BigDecimal a = new BigDecimal("10.5");
     * BigDecimal b = new BigDecimal("2.5");
     * BigDecimal c = a.add(b); // 加法运算
     * BigDecimal d = a.subtract(b); // 减法运算
     * BigDecimal e = a.multiply(b); // 乘法运算
     * BigDecimal f = a.divide(b); // 除法运算
     * BigDecimal g = a.remainder(b); // 取余运算
     *
     * @param smokeInfos 烟的基本信息
     * @return 返回经过计算后的map集合
     * <p>
     * //需要四舍五入
     * smokeInfo.setRealBarRate(new DecimalFormat("0.00%").format(barProfit.divide(realSalePriceDec, 4, RoundingMode.HALF_UP)));
     */
    @Override
    @MethodEventDescription(event = "compute order map")
    public Map<String, Object> getDataMap(List<ExcelSmokeInfo> smokeInfos) {
        int totalNum = 0;
        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal estimateTotalPrice = new BigDecimal("0");
        BigDecimal suggestSellProfit = new BigDecimal("0");
        BigDecimal averagePrice = new BigDecimal("0");
//        常规数量
        int normalSmoke = 0;
//        异型数量
        int abnormalSmoke = 0;

        BigDecimal realSellTotalPrice = new BigDecimal("0");
        BigDecimal realSellTotalProfit = new BigDecimal("0");
        for (ExcelSmokeInfo smokeInfo : smokeInfos) {
//            数量
            String orderNum = smokeInfo.getOrderNum();
//            批发价
            String wholesalePrice = smokeInfo.getWholesalePrice();
//            单个商品总价
            String singlePrice = smokeInfo.getSinglePrice();
//            建议售卖价
            String suggestedSellPrice = smokeInfo.getSuggestedSellPrice();
//            合计：
//            数量合计
            totalNum += Integer.parseInt(orderNum);
//            总烟款合计
            BigDecimal bigDecimalWholesalePrice = new BigDecimal(singlePrice);
            totalAmount = totalAmount.add(bigDecimalWholesalePrice);
//            建议售卖价总价合计
            BigDecimal bigDecimalSinglePrice = new BigDecimal(suggestedSellPrice);
            estimateTotalPrice = estimateTotalPrice.add(bigDecimalSinglePrice.multiply(new BigDecimal(orderNum)));
//--
            if (smokeInfo.getIsAbnormity().equals("1")) {
                abnormalSmoke += Integer.parseInt(orderNum);
            } else {
                normalSmoke += Integer.parseInt(orderNum);
            }

            realSellTotalPrice = realSellTotalPrice.add(new BigDecimal(smokeInfo.getRealSalePriceBar()).multiply(new BigDecimal(orderNum)));
            realSellTotalProfit = realSellTotalProfit.add(new BigDecimal(smokeInfo.getBarProfit()).multiply(new BigDecimal(orderNum)));
//            --
        }
        String formattedTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        suggestSellProfit = estimateTotalPrice.subtract(totalAmount);
        String suggestSellProfitRateFormat = new DecimalFormat("0.00%").format(suggestSellProfit.divide(estimateTotalPrice, 4, RoundingMode.HALF_UP));
        averagePrice = totalAmount.divide(new BigDecimal(totalNum), 2, BigDecimal.ROUND_HALF_UP);
        Map<String, Object> map = new HashMap<>();

        map.put("nowTime", formattedTime);
        map.put("totalNum", totalNum);
        map.put("totalAmount", totalAmount.toString());
        map.put("estimateTotalPrice", estimateTotalPrice.toString());
        map.put("suggestSellProfit", suggestSellProfit);
        map.put("suggestSellProfitRate", suggestSellProfitRateFormat);
        // TODO: 武建平便利店  这个字段应该是在请求进来的时候初始化，而不是写死，
        map.put("merchantName", "武建平便利店");

        map.put("averagePrice", averagePrice.toString());
        map.put("speciesQuantity", smokeInfos.size());

        map.put("normalSmoke", normalSmoke);
        map.put("abnormalSmoke", abnormalSmoke);

        map.put("realSellTotalPrice", realSellTotalPrice.toString());
        map.put("realSellTotalProfit", realSellTotalProfit.toString());
        map.put("realSellRate", new DecimalFormat("0.00%").format(realSellTotalProfit.divide(realSellTotalPrice, 4, RoundingMode.HALF_UP)));
        return map;
    }

    /**
     * 根据现有的信息返回一个 表格样式map 每个单元格是什么样式
     *
     * @param smokeInfos
     * @param map
     * @return
     */
    private Map<PointXY, CellStyleWY> getExcelCellInfo(List<ExcelSmokeInfo> smokeInfos, Map<String, Object> map) {
        Map<PointXY, CellStyleWY> pointXYCellStyleWYHashMap = new HashMap<>();

        //遍历每一行数据信息颜色的填充
        for (int i = 0; i < smokeInfos.size(); i++) {
            //便利这一行的每一个元素
            for (int j = 0; j < Integer.parseInt(
                    smokeOrderTemplate1Config.getWidthOfColumn()); j++) {
                CellStyleWY cellStyleWY = new CellStyleWY();
                //设置 每一行首个单元格的颜色
                if (j == 0 && "1".equals(smokeInfos.get(i).getIsAbnormity())) {
                    //如果 这个烟是异型，设置红色
                    cellStyleWY.setColorIndex(smokeOrderTemplate1Config.getAllotypeSmokeColor());
                    cellStyleWY.setCellType('0');
                } else {
                    //设置每个单元格的类型，图片或者文本
                    if (j + 1 == Integer.parseInt(
                            smokeOrderTemplate1Config.getImgColumnPosition())) {
                        cellStyleWY.setCellType('1');
                        continue;
                    } else {
                        cellStyleWY.setCellType('0');
                        if (StringUtils.containsNumber(smokeOrderTemplate1Config.getRenderColorColumn(), j + 1)) {
                            ExcelUtil.fillCellColor(cellStyleWY, i, smokeOrderTemplate1Config.getLineColorS());
                        }
                    }
                }
                pointXYCellStyleWYHashMap.put(new PointXY(j, i + 3), cellStyleWY);
            }
        }
        return pointXYCellStyleWYHashMap;
    }

    private List<RowObj> getRemarkRowHeight(List<TemplateRemark> remarkList, List<ExcelSmokeInfo> baseInfo, SmokeOrderTemplate1Config smokeOrderTemplate1Config) {
        List<RowObj> rowObjs = new ArrayList<>();
        int[] listInterval = smokeOrderTemplate1Config.getListInterval();
        int i1 = listInterval[0];
        int i2 = listInterval[1];
        for (int i = 0; i < remarkList.size(); i++) {
            TemplateRemark templateRemark = remarkList.get(i);
            if (templateRemark.getContentList()==null) {
                continue;
            }
            RowObj rowObj = new RowObj();
            rowObj.setRowIndex(i+1+i1+i2+baseInfo.size());
            int size = templateRemark.getContentList().size();
            int height = size * Integer.parseInt(smokeOrderTemplate1Config.getBaseRowHeight());
            rowObj.setRowHeight((short)height);
            rowObjs.add(rowObj);
        }
        return rowObjs;
    }

    private static ByteArrayOutputStream beautification(List<RowObj> rowObjs, byte[] bytes) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Workbook workbook = null;
        try {
            workbook = new HSSFWorkbook(byteArrayInputStream);
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            // 设置指定行的行高
            if (rowObjs != null) {
                for (RowObj rowObj : rowObjs) {
                    Row row = sheet.getRow(rowObj.getRowIndex() - 1);
                    if (row != null) {
                        row.setHeightInPoints(rowObj.getRowHeight());
                    }
                }
            }
            // 保存修改后的Excel文件
            try {
                workbook.write(byteArrayOutputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
            workbook.close();
            byteArrayOutputStream.close();
        } catch (IOException e) {
            log.error("delete fail ,{}", e.getMessage());
        }
        return byteArrayOutputStream;
    }

}
